package com.view;

import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.List;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;

import javax.swing.JPanel;

import com.model.ListBg;
import com.model.Shape;

public class MyPanel extends JPanel implements Runnable {

	//大框架，用于和主框架的交互
	private MyFrame myFrame;
	//存放一个方块的对象
	private Shape shapes = null;
	//
	private ListBg listBg=null;


	
	//初始化
	public MyPanel() {
		shapes =new Shape();
		listBg=ListBg.getListBg();
	}

	@Override
	public void paint(Graphics g) {
		super.paint(g);
		Graphics2D g2d = (Graphics2D) g;
		paintBg(g2d);
		paintShape(shapes.getShapes(), g2d);
	}

	// 绘制游戏的背景
	public void paintBg(Graphics2D g2d) {

		// 游戏的背景是一个黑色的大框
		
		// 绘制大框
		g2d.draw3DRect(15, 0, listBg.getGao(), listBg.getKuan(), true);
		
		//循环绘制小格子
		for(int i=1;i<=listBg.getBg().length;i++){
			for(int j=1;j<=listBg.getBg()[i-1].length;j++){
				// 这个格子的横坐标
				int x = (i - 1) * listBg.getGezi() + 15;
				// 纵坐标
				int y = (j - 1) * listBg.getGezi();
				
				if(listBg.getBg()[i-1][j-1]==0){
					// 里面是一个一个的小个子，格子没有填充颜色
					g2d.setColor(Color.black);
					g2d.draw3DRect(x, y, listBg.getGezi(), listBg.getGezi(), true);
				}
				else{
					//绘制实心的
					g2d.setColor(Color.red);
					g2d.fill3DRect(x, y, listBg.getGezi(), listBg.getGezi(), true);
				}
			}
		}
		
	}

	// 绘制当前的方块
	public void paintShape(int[][] shapes, Graphics2D g2d) {
		// 改变画笔的颜色
		g2d.setColor(Color.blue);
		// 从第一行开始
		for (int i = 0; i < listBg.getGao() / listBg.getGezi(); i++) {
			// 从第一列开始
			for (int j = 0; j < listBg.getKuan() / listBg.getGezi(); j++) {

				// 这个格子的横坐标
				int x = (i) * listBg.getGezi() + 15;
				// 纵坐标
				int y = (j) * listBg.getGezi();
				// 绘制的开关
				boolean flag = false;
				for (int k = 0; k < 4; k++) {
					// 判断是否该绘制
					if (shapes[k][0] == i && shapes[k][1] == j) {
						flag = true;
					}
				}
				g2d.setColor(Color.red);
				// 绘制
				if (flag) {
					g2d.fill3DRect(x, y, listBg.getGezi(), listBg.getGezi(), true);
				}
			}
		}
	}

	

	/**
	 * 多线程绘制
	 */
	@Override
	public void run() {
		
		try {
			while (true) {
				this.repaint();
				Thread.sleep(2000);
				shapes.toXia();
			}
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
	}

	
	

	public MyFrame getMyFrame() {
		return myFrame;
	}

	public void setMyFrame(MyFrame myFrame) {
		this.myFrame = myFrame;
	}

	public Shape getShapes() {
		return shapes;
	}

	public void setShapes(Shape shapes) {
		this.shapes = shapes;
	}

}
